# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Query.vulnerabilitiesCountByDay', feature_category: :vulnerability_management do
  include GraphqlHelpers

  let_it_be(:project) { create(:project) }
  let_it_be(:counts) { { critical: 1, high: 2, medium: 3, low: 4, unknown: 5, info: 6 } }
  let_it_be(:current_user) { create(:user, security_dashboard_projects: [project]) }
  let_it_be(:date) { Date.current }

  let(:fields) do
    <<~QUERY
      date
      critical
      high
      info
      low
      medium
      unknown
    QUERY
  end

  let(:args) { { start_date: 1.day.before(date), end_date: 1.day.after(date) } }
  let(:query) { graphql_query_for('vulnerabilitiesCountByDay', args, query_graphql_field('nodes', {}, fields)) }

  before do
    stub_licensed_features(security_dashboard: true)
    post_graphql(query, current_user: current_user)
  end

  context 'when user does not have permission to access the security dashboard of the project' do
    context 'when project has statistics' do
      let_it_be(:statistic) { create(:vulnerability_historical_statistic, project: project, date: date, **counts) }

      it_behaves_like 'a working graphql query that returns data' do
        it 'returns zero for all counts' do
          expect(graphql_data.dig('vulnerabilitiesCountByDay', 'nodes')).to all(include(
            { 'critical' => 0, 'high' => 0, 'medium' => 0, 'low' => 0, 'info' => 0, 'unknown' => 0 }
          ))
        end
      end
    end
  end

  context 'when user has permission to access the security dashboard of the project' do
    before_all do
      project.add_developer(current_user)
    end

    context 'when dashboard does not have statistics' do
      let_it_be(:counts) { { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, info: 0 } }

      it_behaves_like 'a working graphql query that returns data' do
        it 'returns the statistics' do
          expected = [
            { 'date' => 1.day.before(date).to_s },
            { 'date' => date.to_s },
            { 'date' => 1.day.after(date).to_s }
          ].map { |data| data.merge(counts.stringify_keys) }

          expect(graphql_data.dig('vulnerabilitiesCountByDay', 'nodes')).to match_array(expected)
        end
      end
    end

    context 'when project has statistics' do
      let_it_be(:statistic) { create(:vulnerability_historical_statistic, project: project, date: date, **counts) }

      it_behaves_like 'a working graphql query that returns data' do
        it 'returns the statistics' do
          expect(graphql_data.dig('vulnerabilitiesCountByDay', 'nodes')).to include(
            { 'date' => date.to_s }.merge(counts.stringify_keys)
          )
        end
      end
    end
  end
end
